package com.lzht.games.room.service.impl;

import com.lzht.games.room.cache.RedisCache;
import com.lzht.games.room.cache.RoomCache;
import com.lzht.games.room.common.KeyConstant;
import com.lzht.games.room.model.Address;
import com.lzht.games.room.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Create by weishuaiding on 2018/12/11 17:46
 */
@Component
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RedisCache cache;

    @Override
    public void addRoomUser(Integer roomId, Address address) {
        RoomCache.addRoomUser(roomId, address);

        String key = KeyConstant.ROOM_ADDRESS + roomId;
        cache.addSet(key, address);
    }

    @Override
    public void removeRoomUser(Integer roomId, Integer userId) {
        Address address = RoomCache.removeRoomUser(roomId, userId);

        String key = KeyConstant.ROOM_ADDRESS + roomId;
        cache.delSet(key, address);
    }

    @Override
    public Set<Address> getRoomUsers(Integer roomId) {
        Set<Address> addressSet = RoomCache.getRoomUsers(roomId);
        if (addressSet == null) {
            String key = KeyConstant.ROOM_ADDRESS + roomId;
            addressSet = cache.getSets(key, Address.class);

            if (addressSet != null) {
                RoomCache.initRoomUsers(roomId, addressSet);
            }
        }
        return addressSet;
    }
}
